//
//  ViewController.m
//  bleIOSSdkDemo
//
//  Created by 董海伟 on 2019/2/6.
//  Copyright © 2019 董海伟. All rights reserved.
//

#import "ViewController.h"
#import "bleIOSSdk.h"
#import "bleHeader.h"
#import "MBProgressHUD/MBProgressHUD+MoreExtensions.h"
#import "PeripheralViewController.h"

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property(nonatomic,strong)    UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *peripheralDataArray;
@property (strong, nonatomic)  bleIOSSdk *bleSdk;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.bleSdk = [[bleIOSSdk alloc] init];
    self.peripheralDataArray = [[NSMutableArray alloc]init];
    [MBProgressHUD showTipHUDAddedTo:self.view WithLabel:@"准备打开设备"];
    
    [self createTableView];
    
    [self.bleSdk initSdk:@"test"];
    
    [self babyDelegate];
}

-(void) dealloc{
    [self.bleSdk unInitSdk];
}

//蓝牙网关初始化和委托方法设置
-(void)babyDelegate{
    __weak typeof(self) weakSelf = self;
    BabyBluetooth *baby = [self.bleSdk getBluetoothPtr];
    if(Nil != baby) {
        [baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
            if (central.state == CBManagerStatePoweredOn) {
                [MBProgressHUD showTipHUDAddedTo:self.view WithLabel:@"设备打开成功，开始扫描设备"];
            }
        }];
        
        //设置扫描到设备的委托
        [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
            NSLog(@"搜索到了设备:%@",peripheral.name);
            
            [weakSelf insertTableView:peripheral advertisementData:advertisementData RSSI:RSSI];
        }];
        
        //设置查找设备的过滤器
        [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
            
            //设置查找规则是名称大于0 ， the search rule is peripheral.name length > 0
            if (peripheralName.length >0) {
                return YES;
            }
            return NO;
        }];
    }
}

- (void)createTableView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT- 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

//插入table数据
-(void)insertTableView:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    NSArray *peripherals = [self.peripheralDataArray valueForKey:@"peripheral"];
    if(![peripherals containsObject:peripheral]) {
        NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:peripherals.count inSection:0];
        [indexPaths addObject:indexPath];
        
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setValue:peripheral forKey:@"peripheral"];
        [item setValue:RSSI forKey:@"RSSI"];
        [item setValue:advertisementData forKey:@"advertisementData"];
        [self.peripheralDataArray addObject:item];
        
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.peripheralDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSDictionary *item = [self.peripheralDataArray objectAtIndex:indexPath.row];
    CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
    NSDictionary *advertisementData = [item objectForKey:@"advertisementData"];
    NSNumber *RSSI = [item objectForKey:@"RSSI"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //peripheral的显示名称,优先用kCBAdvDataLocalName的定义，若没有再使用peripheral name
    NSString *peripheralName;
    if ([advertisementData objectForKey:@"kCBAdvDataLocalName"]) {
        peripheralName = [NSString stringWithFormat:@"%@",[advertisementData objectForKey:@"kCBAdvDataLocalName"]];
    }else if(!([peripheral.name isEqualToString:@""] || peripheral.name == nil)){
        peripheralName = peripheral.name;
    }else{
        peripheralName = [peripheral.identifier UUIDString];
    }
    
    cell.textLabel.text = peripheralName;
    //信号和服务
    cell.detailTextLabel.text = [NSString stringWithFormat:@"RSSI:%@",RSSI];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //停止扫描
    BabyBluetooth *baby = [self.bleSdk getBluetoothPtr];
    if(Nil != baby) {
        [baby cancelScan];
        
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        PeripheralViewController *vc = [[PeripheralViewController alloc]init];
        NSDictionary *item = [self.peripheralDataArray objectAtIndex:indexPath.row];
        CBPeripheral *peripheral = [item objectForKey:@"peripheral"];
        vc.currPeripheral = peripheral;
        vc.baby = baby;
        vc.bleSdk=self.bleSdk;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
